package com.dabai.iot.core.task;

import cn.hutool.core.date.DateUtil;
import com.dabai.common.core.enums.YnEnum;
import com.dabai.common.core.utils.DateUtils;
import com.dabai.iot.core.entity.DeviceEntity;
import com.dabai.iot.core.service.IDeviceCountService;
import com.dabai.iot.core.service.IDeviceService;
import com.dabai.system.api.RemoteTenantService;
import com.dabai.system.api.domain.vo.RemoteTenantVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
@EnableScheduling
@RequiredArgsConstructor
public class DeviceOnlineCounter {

    private final IDeviceService deviceService;
    private final IDeviceCountService deviceCountService;

    @DubboReference
    private final RemoteTenantService remoteTenantService;

    /**
     * 每日0点初始化计数器
     * 从数据库加载当前在线设备
     */
    @Scheduled(cron = "0 0 0 * * ?")
    // 测试，每隔 5 分执行一次
//    @Scheduled(cron = "0 0/5 * * * ?")
    public void initDailyCounter() {
        Date now = DateUtils.getNowDate();

        // 获取所有企业列表
        List<RemoteTenantVo> tenantList = remoteTenantService.queryList();

        for (RemoteTenantVo tenant : tenantList) {
            String tenantId = tenant.getTenantId();

            // 获取缓存中昨日的统计数量
            long yesterdayCount = deviceCountService.getDeviceOnlineCount(tenantId, DateUtil.yesterday());
            log.info("租户[{}]昨日最大设备在线数量为：{}", tenantId, yesterdayCount);

            // 保存昨日数据到数据库
            deviceCountService.saveOnlineCount(tenantId, DateUtil.yesterday(), yesterdayCount);

            // 查询当前在线设备数量
            Set<Long> onlineDeviceIds = deviceService
                .lambdaQuery()
                .eq(DeviceEntity::getTenantId, tenantId)
                .eq(DeviceEntity::getIsOnline, YnEnum.YES.getValue())
                .list()
                .stream()
                .map(DeviceEntity::getId)
                .collect(Collectors.toSet());

            // 加入缓存中
            deviceCountService.updateDeviceOnlineCount(tenantId, now, onlineDeviceIds);
            log.info("当前时刻 [{}] 租户[{}]设备在线数量为：{}", DateUtils.formatDateTime(now), tenantId, onlineDeviceIds.size());
        }
    }

}
